<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import {
  WorkTypeFileReport,
  deleteFiles,
  addCheckProblems,
  getFileApi,
  getPalyFileApi,
  AddFileBrowseApi,
  CutVideoFileApi,
  CheckedProblem
} from '@/api/table'
import { getProblemTypesApi, GetWorkTypesApi } from '@/api/role'
import { ref, unref, reactive } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { BaseButton } from '@/components/Button'
import { Dialog } from '@/components/Dialog'
import { VideoPlayer } from '@/components/VideoPlayer'
import { Form, FormSchema } from '@/components/Form'
import { useValidator } from '@/hooks/web/useValidator'
import { useForm } from '@/hooks/web/useForm'
import DPlayer from 'dplayer'
import { ElMessage, ElMessageBox, ElDivider, ElInput, ElTooltip } from 'element-plus'
import { useButtonPermiss } from '@/utils/buttonpermiss'
import { rowStyleFC, handleParams } from '@/views/DataCenter/util'
import * as XLSX from 'xlsx'
const haspermiss = ref<String[]>([])
const getUseButtonPermiss = () => {
  useButtonPermiss().then((res) => {
    haspermiss.value = res
  })
}
getUseButtonPermiss()

const searchRef = ref()
// console.log('useButtonPermiss haspermiss', haspermiss)
const { t } = useI18n()
const { required } = useValidator()
const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods
const columns: TableColumn[] = [
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'workTypeName',
    label: '作业类型',
    sortable: true
    // slots: {
    //   default: ({ row }: any) => {
    //     const workTypeColor = row.workTypeColor || '#000'
    //     const style = { color: workTypeColor }
    //     return (
    //       <>{workTypeColor ? <span style={style}>{row.workTypeName}</span> : row.workTypeName}</>
    //     )
    //   }
    // }
  },

  //   {
  //     field: 'depNo',
  //     label: t('userDemo.depNo')
  //   },
  //   {
  //     field: 'depName',
  //     label: t('userDemo.departmentName')
  //   },
  //   {
  //     field: 'userNo',
  //     label: t('userDemo.userNo')
  //   },
  //   {
  //     field: 'userName',
  //     label: t('userDemo.username')
  //   },

  {
    field: 'videoCount',
    label: '视频数量'
  },
  {
    field: 'videoLength',
    label: '视频长度'
  },
  {
    field: 'videoSize',
    label: '视频大小'
  },
  {
    field: 'audioCount',
    label: '音频数量'
  },
  {
    field: 'audioSize',
    label: '音频大小'
  },
  {
    field: 'imageCount',
    label: '图片数量'
  },
  {
    field: 'imageSize',
    label: '图片大小'
  },
  {
    field: 'logCount',
    label: '日志数量'
  },
  {
    field: 'logSize',
    label: '日志大小'
  }
]

interface files {
  guid: string
  filePath: string
  fileName: string
}

const showDetail = ref(false)
let saveLoading = ref(false)
const showVideoLoading = ref(false)
let currentRow = ref<files | null>(null)
let videoUrl = ref()
const videoRef = ref()
let isHaveFile = ref(false)
const look = async (row: files) => {
  showDetail.value = true
  showVideoLoading.value = true
  currentRow.value = row
  time.value = ''
  AddFileBrowseApi({ fileGuid: row.guid })
  const res = await CheckedProblem({ fileGuid: row.guid })
  console.log('CheckedProblem-----------', !res)
  isHaveFile.value = !res
  getPalyFileApi({ fileGuid: row.guid })
    .then((res) => {
      videoUrl.value = res.data
      // const videoFile = new Blob([res.data], {
      //   // type: 'video/mp4'
      //   type: 'video/mov'
      // })
      // videoUrl.value = URL.createObjectURL(videoFile)
      // console.log('videoUrl.value---', unref(videoUrl.value))
      // const dp = new DPlayer({
      //   container: videoRef.value,
      //   autoplay: true,
      //   theme: '#FADFA3',
      //   loop: true,
      //   lang: 'zh-cn',
      //   screenshot: true,
      //   hotkey: true,
      //   preload: 'auto',
      //   // logo: 'logo.png',
      //   volume: 0.7,
      //   mutex: true,
      //   video: {
      //     url: videoUrl.value,
      //     // url: '../../assets/video/1.MOV',
      //     type: 'flv'
      //     // type: 'webtorrent'
      //   }
      // })

      showVideoLoading.value = false
    })
    .catch(() => {
      videoUrl.value = ''
      showVideoLoading.value = false
      ElMessage({
        message: '视频加载失败',
        type: 'error'
      })
    })
}

const save = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    console.log(formData, currentRow)
    if (formData) {
      formData.fileGuid = currentRow.value?.guid
      saveLoading.value = true
      let res = await addCheckProblems(formData).finally(() => {
        saveLoading.value = false
      })
      const timeArr = time.value.split('~')
      if (timeArr.length == 2) {
        CutVideoFileApi({ fileGuid: currentRow.value?.guid, start: timeArr[0], end: timeArr[1] })
      }

      if (res) {
        showDetail.value = false
      }
    }
  }
}
const delLoading = ref(false)
const ids = ref<string[]>([])
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await WorkTypeFileReport({
      pageNo: unref(currentPage),
      pageRow: unref(pageSize),
      pageModel: { ...unref(searchParams) }
    })
    return {
      list: res.data.pageModels || [],
      total: res.data.totalCount || 0
    }
  },
  fetchDelApi: async () => {
    const res = await deleteFiles(unref(ids))
    return !!res
  }
})

const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = handleParams(params)
  //   searchParams.value = getList()
}
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'workType',
    label: '作业类型',
    component: 'Select',
    componentProps: {
      clearable: true,
      filterable: true,
      props: {
        label: 'typeName',
        // value: 'guid'
        value: 'typeName'
      }
    },
    optionApi: async () => {
      const res = await GetWorkTypesApi({ pageFlag: false })
      return res.data?.pageModels || []
    }
  },
  {
    field: 'date',
    label: '日期筛选',
    component: 'DatePicker',
    componentProps: {
      style: { width: '340px' },
      type: 'datetimerange',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      StartPlaceholder: 'Start date',
      EndPlaceholder: 'End date'
    }
  }
])
const delData = async (row) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.guid] : elTableExpose?.getSelectionRows().map((v) => v.guid) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
interface ProblemType {
  // typeName?: string
  // guid?: string
  label: string
  value: string
}

const typelist = ref<ProblemType[]>([])

const getTypeList = async () => {
  let res = await getProblemTypesApi({})
  if (res.data) {
    res.data.map((item) => {
      typelist.value.push({
        label: item.typeName,
        value: item.guid
      })
    })
  }
}

getTypeList()
const time = ref('')
const formSchema = ref<FormSchema[]>([
  {
    field: 'problemType',
    label: t('problem.problemType'),
    component: 'Select',
    componentProps: {
      clearable: true,
      placeholder: '请选择问题类型'
    },
    optionApi: async () => {
      return typelist.value
    }
  },

  {
    field: 'problemContent',
    label: t('problem.problemContent'),
    component: 'Input',
    componentProps: {
      type: 'textarea',
      inputStyle: { height: '180px' }
    }
  },

  {
    field: 'remark',
    label: t('common.remark'),
    component: 'Input',
    componentProps: {
      type: 'textarea',
      inputStyle: { height: '120px' }
    }
  }
])

const rules = reactive({
  problemType: [required()],
  problemContent: [required()]
})

const getVideoTime = (type) => {
  const currentTime = videoRef.value.currentTime
  if (type == 'start') {
    time.value = Math.ceil(currentTime) + '~' + videoRef.value.duration
  } else {
    if (!time.value) {
      return ElMessage.error('请先设置问题出现的开始时间')
    } else {
      const timeArr = time.value.split('~')
      const startTime = timeArr[0]
      if (currentTime < startTime) {
        return ElMessage.error('结束时间小于开始时间')
      }
      time.value = startTime + '~' + Math.ceil(currentTime)
    }
  }
  setValues({ tiem: time.value })
  console.log('当前播放时间:', time.value)
}
const canvas = ref()
// const saveImg = () => {
//   canvas.value.width = 400
//   canvas.value.height = 400
//   console.log('canvas', unref(canvas))
//   // 暂停视频，防止继续播放影响截图内容
//   videoRef.value.pause()
//   canvas.value.crossOrigin = 'Anonymous'
//   canvas.value
//     .getContext('2d')!
//     .drawImage(videoRef.value, 0, 0, canvas.value.width, canvas.value.height)
//   // canvas.value.toBlob((blob) => {
//   //   if (blob) {
//   //     const imgUrl = URL.createObjectURL(blob)
//   //     const a: HTMLAnchorElement = document.createElement('a')
//   //     // 设置<a>元素的属性
//   //     a.href = imgUrl
//   //     a.download = '截屏.png'
//   //     // 将<a>元素添加到文档中
//   //     document.body.appendChild(a)
//   //     // 触发点击事件
//   //     a.click()
//   //     URL.revokeObjectURL(a.href)
//   //     // 移除<a>元素
//   //     document.body.removeChild(a)
//   //   }
//   // })
//   const imgUrl = canvas.value.toDataURL('image/png')

//   const a: HTMLAnchorElement = document.createElement('a')
//   // 设置<a>元素的属性
//   a.href = imgUrl
//   a.download = '截屏.png'
//   // 将<a>元素添加到文档中
//   document.body.appendChild(a)
//   // 触发点击事件
//   a.click()
//   URL.revokeObjectURL(a.href)
//   // 移除<a>元素
//   document.body.removeChild(a)
// }
interface tableExpose {
  作业类型: string

  视频数量: string
  视频长度: string
  视频大小: string
  音频数量: string
  音频大小: string
  图片数量: string
  图片大小: string
  日志数量: string
  日志大小: string
  视频时长不达标?: number
  视频容量不达标?: number
  使用率?: string
  异常告警?: number
}

const handleData = async () => {
  let arr: tableExpose[] = []

  const res = await WorkTypeFileReport({
    pageFlag: false,
    pageModel: { ...unref(searchParams) }
  })
  const list = res.data.pageModels
  list.map((item) => {
    arr.push({
      作业类型: item.workTypeName,
      视频数量: item.videoCount,
      视频长度: item.videoLength,
      视频大小: item.videoSize,
      音频数量: item.audioCount,
      音频大小: item.audioSize,
      图片数量: item.imageCount,
      图片大小: item.imageSize,
      日志数量: item.logCount,
      日志大小: item.logSize
    })
  })
  return arr
}
const exportToExcel = async () => {
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new()
  // 创建一个工作表
  const worksheet = XLSX.utils.json_to_sheet(await handleData())

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 生成Excel文件
  XLSX.writeFile(workbook, '作业类型情况统计分析.xlsx')
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <div
      style="display: flex; justify-content: end; margin-bottom: 10px"
      v-if="haspermiss.includes('导出')"
    >
      <BaseButton type="primary" @click="exportToExcel">{{ t('exampleDemo.exprot') }}</BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :reserveIndex="true"
      :columns="columns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
</template>
<style scoped>
.dplayer-menu :deep(.dplayer-mask) {
  display: none !important;
}
.row_d {
  display: flex;
  width: 100%;
  /* align-items: center; */
}
.rombox {
  flex: 2;
  margin-left: 20px;
}
.downstyle {
  margin-right: 20px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  line-height: 1;
  height: 32px;
  white-space: nowrap;
  cursor: pointer;
  color: #fff;
  text-align: center;
  box-sizing: border-box;
  outline: 0;
  transition: 0.1s;
  font-weight: 500;
  -webkit-user-select: none;
  user-select: none;
  vertical-align: middle;
  -webkit-appearance: none;
  background-color: #529b2e;
  border: var(--el-border);
  border-color: #529b2e;
  padding: 8px 15px;
  font-size: 14px;
  border-radius: 4px;
  text-decoration: none;
}
</style>
